import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_view/photo_view_gallery.dart';

typedef PageChanged = void Function(int index);

class PictureOverview extends StatefulWidget {
  final List imageItems; //图片列表
  final int defaultIndex; //默认第几张
  final PageChanged pageChanged; //切换图片回调
  final Axis direction; //图片查看方向
  final Decoration decoration; //背景设计
  final  int type;
  PictureOverview(
      {this.imageItems,
      this.defaultIndex = 1,
      this.pageChanged,
      this.direction = Axis.horizontal,
      this.type=1,
      this.decoration})
      : assert(imageItems != null);
  @override
  _PictureOverviewState createState() => _PictureOverviewState();
}

class _PictureOverviewState extends State<PictureOverview> {
  int currentIndex;
  @override
  void initState() {
    super.initState();
    // TODO: implement initState
    currentIndex = widget.defaultIndex;
  }

  saveNetworkImg(String imgUrl) async {
    var response = await Dio()
        .get(imgUrl, options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        quality: 60,
        name: "hello");
    if (result['isSuccess']) {
      Fluttertoast.showToast(msg: "保存网络图片成功，保存路径为${result['filePath']}");
    }
  }

  saveFile() async {
    Directory storageDir = await getApplicationDocumentsDirectory();
    String storagePath = storageDir.path;
    String savePath = storagePath + "/app-DOudbVCUZyyn.pdf";

    ///temp.png这个自己命名
    File file = new File(savePath);
    var response = await Dio().get(
        "http://cgq-blog.oss-cn-guangzhou.aliyuncs.com//moment/2022526/app-DOudbVCUZyyn.pdf",
        options: Options(responseType: ResponseType.bytes));
    try {
      await file
          .writeAsBytes(response.data, mode: FileMode.append)
          .whenComplete(
              () => {Fluttertoast.showToast(msg: "保存成功"), print(savePath)});

      //  await  response.data.writeToFile(file);

    } catch (e) {
      print(e);
    }
    //  response.data.writeToFile(file);
    //  file.writeAsBytesSync(response.data);
    //  print(savePath);
    //   Fluttertoast.showToast(msg: "保存网络图片成功，保存路径为$savePath");
  }

  saveVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    String fileUrl =
        "http://cgq-blog.oss-cn-guangzhou.aliyuncs.com//moment/2022526/app-yQVMloIebkKv.mp4";
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      print((count / total * 100).toStringAsFixed(0) + "%");
    });
    final result = await ImageGallerySaver.saveFile(savePath);
    if (result['isSuccess']) {
      Fluttertoast.showToast(msg: "保存视频成功，保存路径为${result['filePath']}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Stack(
        children: [
          Container(
              child: PhotoViewGallery.builder(
                  scrollPhysics: const BouncingScrollPhysics(),
                  builder: (BuildContext context, int index) {
                    return PhotoViewGalleryPageOptions(
                      imageProvider:widget.type!=2? NetworkImage(widget.imageItems[index].url): FileImage(
                              File(widget.imageItems[index].url)
                            ),
                    );
                  },
                  scrollDirection: widget.direction,
                  itemCount: widget.imageItems.length,
                  backgroundDecoration:
                      widget.decoration ?? BoxDecoration(color: Colors.black),
                  pageController:
                      PageController(initialPage: widget.defaultIndex),
                  onPageChanged: (index) => setState(() {
                        currentIndex = index;
                        if (widget.pageChanged != null) {
                          widget.pageChanged(index);
                        }
                      }))),
          Positioned(
            bottom: 20,
            child: Container(
                alignment: Alignment.center,
                width: MediaQuery.of(context).size.width,
                child: Text("${currentIndex + 1}/${widget.imageItems.length}",
                    style: TextStyle(
                      decoration: TextDecoration.none,
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w400,
                      shadows: [
                        Shadow(color: Colors.black, offset: Offset(1, 1)),
                      ],
                    ))),
          ),
          Positioned(
            //右上角关闭
            top: 40,
            right: 40,
            child: Container(
              alignment: Alignment.centerLeft,
              width: 20,
              child: GestureDetector(
                onTap: () {
                  //隐藏预览
                  Navigator.pop(context);
                },
                child: Icon(Icons.close_rounded, color: Colors.white),
              ),
            ),
          ),
          Positioned(
            bottom: 20,
            right: 40,
            child: Container(
              alignment: Alignment.centerLeft,
              width: 20,
              child: GestureDetector(
                onTap: () {
                  saveNetworkImg(widget.imageItems[currentIndex].url);
                },
                child: Icon(Icons.download, color: Colors.white),
              ),
            ),
          ),
          Positioned(
            //数量显示
            right: 20,
            top: 20,
            child: Text(
              '${currentIndex + 1}/${widget.imageItems.length}',
              style: TextStyle(color: Colors.black),
            ),
          )
        ],
      ),
    );
  }
}
